<?php
Yii::import('Cms.helpers.DataHelper');
class TemplateContentDropDownList extends CInputWidget
{
    public $htmlOptions = array('prompt'=>'---Select---');
    public $exclude = array();
    public $excludeContent = array();
    public $exceptMasterLayout = FALSE;
    
    private $_data;
    
    public function init()
    {
        parent::init();
        if (is_null($this->_data))
        {
            $group = '';
            if (isset($this->htmlOptions['group']))
            {
                $group = $this->htmlOptions['group'];
                unset($this->htmlOptions['group']);
            }
            $models = FSM::run('Cms.TemplateContent.getList', array('status'=>true,'group'=>$group,'exceptMasterLayout'=>$this->exceptMasterLayout))->models;
            $data = array();
            if (count($models))
            {
                foreach ($models as $model)
                {
                    if (count($this->excludeContent) && in_array($model->id, $this->excludeContent)) continue;
                    if (count($this->exclude) && in_array($model->template_id, $this->exclude)) continue;
                    if (is_object($model->template))
                    {
                        $log = $model->log;
                        if (empty($log) === false)
                        {
                            $log = strip_tags($log);
                            list($log,) = explode("\n", $log, 2);
                            $logShort = DataHelper::truncateWords($log, 10);
                            $log = ' - '.(strlen($log) > strlen($logShort) ? $logShort.'...' : $logShort);
                        }
                        $data[$model->template->name][$model->id] = 'rev#'.$model->revision_id.$log;
                    }
                }
            }
            $this->_data = $data;
            //Yii::trace('$data '.CVarDumper::dumpAsString($data), 'TemplateContentDropDownList');
        }
    }
    
    public function run()
    {
        if (is_object($this->model))
            echo CHtml::activeDropDownList($this->model, $this->attribute, $this->getData(), $this->htmlOptions);
        else
            echo CHtml::dropDownList($this->name, $this->value, $this->getData(), $this->htmlOptions);
    }
    
    public function getData()
    {
        return $this->_data;
    }
}